//
//  ViewController.m
//  wi-fi-party-remade-3
//
//  Created by ken on 2021/10/30.
//

#import "ViewController.h"


@interface ViewController ()

@end

@implementation ViewController


- (IBAction)singSwitchToggled:(UISwitch *)sender {
    if(sender.on){
        startSinging(self->unit);
    }else{
        stopSinging(self->unit);
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    RPSystemBroadcastPickerView *picker=[[RPSystemBroadcastPickerView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
    [self.view addSubview:picker];
    //Make an HTTP get to make sure network is fine.
    //1. 本地网络权限  2. 允许使用网络（不允许，Wi-Fi，Wi-Fi和流量）
    NSURL *url=[NSURL URLWithString:@"http://192.168.3.1"];
    [NSData dataWithContentsOfURL:url];
    
    get_sendaddr();
    struct sockaddr_in *self_addr=get_selfaddr();

    
    int s=socket(AF_INET, SOCK_DGRAM, 0);
//    send_addr=get_sendaddr();
    
    int flag=1;
    //Reuse address (So the in-app recording could bind the same addr)
    if(setsockopt(s, SOL_SOCKET, SO_REUSEADDR,&flag,sizeof(flag))!=0){
        printf("Failed to enable address reuse\n");
    }
    
    
    Receiver *r=new Receiver(s);
    Trackreceiver *music_receiver=new Trackreceiver();
    Trackreceiver *vocal_receiver=new Trackreceiver();
    Mixer<Trackreceiver> *sound_mixer=new Mixer<Trackreceiver>();
    sound_mixer->addSource(music_receiver);
    sound_mixer->addSource(vocal_receiver);
    Channel *music_channel=new Channel(music,channel_unreliable,1,s,[=](Packet *p){
        if(p->from_addr->sin_addr.s_addr!=self_addr->sin_addr.s_addr){
            music_receiver->receiveSound(p);
        }
        return true;
    });
    Channel *vocal_channel=new Channel(vocal,channel_unreliable,1,s,[=](Packet *p){
        vocal_receiver->receiveSound(p);
        return true;
    });
    r->addChannel(music_channel);
    r->addChannel(vocal_channel);
    
    self->unit=startAudioUnit(sound_mixer,music_receiver,vocal_channel);
    r->receive_forever();
    //self->r->receive_blocking();
    
}


@end
